//
//  XLTalkedPeopleViewController.m
//  XiangLove
//
//  Created by feng song on 2017/12/20.
//  Copyright © 2017年 BAOMIHUA.COM. All rights reserved.
//

#import "XLTalkedPeopleViewController.h"
 
#import "AoiroSoraLayout.h"
#import "XLHTTPSessionManager+UserInfo.h"
#import "XLAccountManager.h"
#import "XLUserInfoModel.h"
#import <ReactiveCocoa.h>
#import "XLTalkedPeopleModle.h"
#import "XLTalkedPeopleCell.h"
#import "MJRefresh.h"
#import "IMAChatViewController.h"
#import "XLPersonPageViewController.h"

@interface XLTalkedPeopleViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,AoiroSoraLayoutDelegate>

@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)NSMutableArray   *modelArray;
@property (nonatomic,copy  )NSString         *page;
@property (nonatomic,copy  )NSString         *firstUpdata;
@property (nonatomic,strong)XLUserInfoModel  *userInfoModel;
@property (nonatomic,strong)XLTalkedPeopleModle *talkedPeopleModle;

@end

@implementation XLTalkedPeopleViewController

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
    //return UIStatusBarStyleDefault;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kWhiteColor;
    self.fd_prefersNavigationBarHidden = NO;
    self.automaticallyAdjustsScrollViewInsets = YES;
    self.navigationItem.title = @"聊过的人";
//    self.navigationController.navigationBar.barTintColor = RGB_HEX(0x1a1926);
//    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    [self  showBackButton:nil];
    self.page = @"0";
    [self addCollectionView];
    [self requrstTalkedPeoplePage:@"0"];
}

-(void)addCollectionView
{
    AoiroSoraLayout * layout = [[AoiroSoraLayout alloc]init];
    layout.interSpace = 0;
    layout.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    layout.colNum     = 1; 
    layout.delegate   = self;
    
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, XQScreenW, XQScreenH) collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = RGB_HEX(0xffffff);
    [_collectionView registerClass:[XLTalkedPeopleCell class] forCellWithReuseIdentifier:@"cell"];
    _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(handelGCHeaderTableView)];
    _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(handelGCFootTableView)];
    [self.view addSubview:_collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

- (NSMutableArray *)modelArray
{
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

- (void)requrstTalkedPeoplePage:(NSString *)page
{
    
    if ([page isEqualToString:@"0"]) {
        static dispatch_once_t available;
        //只执行一次
        dispatch_once(&available, ^{
            [MBProgressHUD hideHUDForView:self.view];
            self.firstUpdata = @"1";
        });
    }
    [MBProgressHUD showMessage:@"" toView:self.view];
    self.userInfoModel = [[XLAccountManager shareInstance] model];
    [[[XLHTTPSessionManager sharedManager] getTalkedPeopleNumbersuserld:self.userInfoModel.Id pageIndex:self.page pageCount:@"" secretKey:self.userInfoModel.SecretKey] subscribeNext:^(id x) {
        NSLog(@"聊过的人==%@",x);
        NSArray * listAry = x;
        if (listAry.count > 0) {
            
            [self getJsonArray:listAry];
        }
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD hideHUDForView:self.view];
    } error:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        NSLog(@"%@", error);
        if (error.code == 1001) {
            [MBProgressHUD showContent:@"验签失败" toView:self.view];
        }else if (error.code == 1002){
            [MBProgressHUD showContent:@"无数据" toView:self.view];
            
        }else if (error.code == 1003){
            
            [MBProgressHUD showContent:@"请求参数错误" toView:self.view];
        }else if (error.code == 1004){
            [MBProgressHUD showContent:@"票证已过期" toView:self.view];
        }
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        
    }];
}

- (void)getJsonArray:(NSArray *)array {
    if ([array isKindOfClass:[NSNull class]] || array.count == 0 || array == nil) {
        
    } else {
        if ([self.page isEqualToString:@"0"]) {
            [self.modelArray removeAllObjects];
        } else {
            
        }
        [self.modelArray addObjectsFromArray:array];
    }
    [self.collectionView reloadData];
}


#pragma mark - 下拉刷新
- (void)handelGCHeaderTableView {
    self.firstUpdata = @"1";
    self.page = @"0";
    [self requrstTalkedPeoplePage:self.page];
}

#pragma mark - 上拉加载
- (void)handelGCFootTableView {
    self.firstUpdata = @"1";
    self.page = [NSString stringWithFormat:@"%d", [self.page intValue] + 1];
    [self requrstTalkedPeoplePage:self.page];
}

#pragma mark -- 返回每个item的高度
- (CGFloat)itemHeightLayOut:(AoiroSoraLayout *)layOut indexPath:(NSIndexPath *)indexPath
{
    NSInteger intger = 72;
    return intger;
}

#pragma mark -- collectionView 的分组个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

#pragma mark -- item 的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.modelArray.count;
    
}

#pragma mark -- cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    XLTalkedPeopleModle * model = self.modelArray[indexPath.row];
    XLTalkedPeopleCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.dataModels = model;
    cell.backgroundColor = kWhiteColor;
    return cell;
}

#pragma mark -- 选中某个cell
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    XLTalkedPeopleModle *model = (XLTalkedPeopleModle *)self.modelArray[indexPath.row ];
    
    //跳转私聊界面
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//
        [[TIMFriendshipManager sharedInstance] GetUsersProfile:@[NSStringFormat(@"%@",model.UserId)] succ:^(NSArray *friends) {
            for (TIMUserProfile *pro in friends)
            {
                IMAUser *user = [[IMAUser alloc] initWithUserInfo:pro];
                dispatch_async(dispatch_get_main_queue(), ^{
                    IMAChatViewController *chat = [[IMAChatViewController alloc] initWith:user];
//                    chat.isAnchor =;
                    [self.navigationController pushViewController:chat animated:YES ];
                });
            }
        } fail:^(int code, NSString *msg) {
            NSLog(@"msg");
        }];
        return;
    }

    
    XLPersonPageViewController *vc = [[XLPersonPageViewController alloc] init];
    vc.userId = model.UserId;
    [self.navigationController pushViewController:vc animated:YES];
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
